package com.yl.chainStore.services.impl.warehouse

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper
import com.yl.chainStore.common.LockObjects
import com.yl.chainStore.common.enums.Status
import com.yl.chainStore.common.enums.TypeEnum
import com.yl.chainStore.entity.warehouse.WarehouseOutOrder
import com.yl.chainStore.entity.warehouse.WarehouseOutOrderDetail
import com.yl.chainStore.mapper.warehouse.WarehouseOutOrderDetailMapper
import com.yl.chainStore.mapper.warehouse.WarehouseOutOrderMapper
import com.yl.chainStore.pojo.vo.warehouse.OutBatchCountVo
import com.yl.chainStore.pojo.vo.warehouse.UpdateWarehouseGoodVo
import com.yl.chainStore.services.warehouse.IWarehouseOutOrderService
import com.yl.chainStore.services.warehouse.IWarehouseService
import com.yl.common.ErrorCode
import com.yl.common.control.ResponseBody
import com.yl.common.control.returnError
import com.yl.common.control.returnSuccess
import com.yl.common.getContext
import com.yl.users.services.ICompanyUserService
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import java.util.*

@Service
class WarehouseOutOrderServiceImpl(
	private val warehouseOutOrderMapper: WarehouseOutOrderMapper,
	private val warehouseOutOrderDetailMapper: WarehouseOutOrderDetailMapper,

	): IWarehouseOutOrderService {

	companion object {
		private val log = LoggerFactory.getLogger(IWarehouseOutOrderService::class.java)
	}

	@Autowired
	lateinit var iWarehouseService: IWarehouseService

	@Autowired
	lateinit var iCompanyUserService: ICompanyUserService
	override fun addOrderDetail(detail: WarehouseOutOrderDetail): ResponseBody {
		log.info("出库单：添加出库明细：detail{}", detail)
		warehouseOutOrderDetailMapper.insert(detail)
		return returnSuccess()
	}

	override fun updateDetail(detail: WarehouseOutOrderDetail): ResponseBody {
		log.info("出库单：修改出库明细：detail{}", detail)
		warehouseOutOrderDetailMapper.updateById(detail)
		return returnSuccess()
	}

	override fun delDetail(id: Long): ResponseBody {
		log.info("出库单：删除明细：id{}", id)
		warehouseOutOrderDetailMapper.deleteById(id)
		return returnSuccess()
	}


	override fun getOutOrder(id: Long): WarehouseOutOrder? {
		log.info("仓库订单管理：出库详情：id{}", id)
		return warehouseOutOrderMapper.getOutOrderById(id)
	}

	override fun getOutOrderDetails(id: Long): List<WarehouseOutOrderDetail> {
		log.info("仓库订单管理：出库订单明细列表：id{}", id)
		return warehouseOutOrderDetailMapper.getListByOrderId(id)
	}

	override fun completeOutOrder(id: Long): ResponseBody {
		log.info("仓库订单管理：出库确认：id{}", id)
		val outOrder =
			warehouseOutOrderMapper.selectById(id) ?: return returnError(ErrorCode.DATA_IS_NOT_FIND, "出库单未找到")
		outOrder.details =
			warehouseOutOrderDetailMapper.getListByOrderId(id)
		return completeOutOrder(outOrder)
	}

	override fun completeOutOrder(outOrder: WarehouseOutOrder): ResponseBody {
		log.info("仓库订单管理：出库确认：outOrder{}", outOrder)

		if (outOrder.status != Status.WAIT_AUDIT) {
			return returnError(ErrorCode.OPERATION_DATA_ERROR, "订单已被处理")
		}
		outOrder.status = Status.COMPLETE

		val dealUserId = getContext().userId
		outOrder.dealUserId = dealUserId
		outOrder.dealTime = Date()
		warehouseOutOrderMapper.updateById(outOrder)
		var i = 1
		if (!outOrder.details.isNullOrEmpty()) {
			val str :String = outOrder.companyId.toString() + "_"+outOrder.deptId.toString()
			synchronized(LockObjects.getWarehouseLock(str)){
				for (detail in outOrder.details!!) {
					log.info("仓库订单管理：出库确认：详情确认：detail{}", detail)
					detail.status = Status.COMPLETE

					val log = UpdateWarehouseGoodVo(
						associatedType = TypeEnum.WAREHOUSE_LOG_TYPE_OUT_ORDER,
						associatedId = outOrder.id,
						remark = detail.remark,
						deptId = outOrder.deptId,
						companyId = outOrder.companyId,
						itemId = detail.itemId,
						goodCount = detail.goodCount,
						detailId = detail.id
					)

					val outResponseBody = iWarehouseService.outWarehouse(detail.outWarehouseGoodBatchId, log)
					if (outResponseBody.code != ErrorCode.SUCCESS.code) {
						return returnError(ErrorCode.OPERATION_DATA_ERROR, "第" + i + "行物品出库失败:" + outResponseBody.msg)
					}
//					detail.sumMoney = (outResponseBody.data as Long)
					val resList = outResponseBody.data as List<*>
					warehouseOutOrderDetailMapper.deleteById(detail.id)
					for(vo in resList){
						vo as OutBatchCountVo
						detail.id = 0
						detail.goodCount = vo.count
						detail.outWarehouseGoodBatchId = vo.id
						detail.price = vo.price
						warehouseOutOrderDetailMapper.insert(detail)
					}
					i++
				}
			}
		}
		return returnSuccess()
	}

	override fun noPassOutOrder(id: Long): ResponseBody {
		log.info("仓库订单管理：审核不通过：id{}", id)
		val outOrder =
			warehouseOutOrderMapper.selectById(id) ?: return returnError(ErrorCode.DATA_IS_NOT_FIND, "未找到出库单")
		if (outOrder.status != Status.WAIT_AUDIT) {
			return returnError(ErrorCode.OPERATION_DATA_ERROR, "订单已被处理")
		}
		val details =
			warehouseOutOrderDetailMapper.selectList(QueryWrapper<WarehouseOutOrderDetail?>().eq("out_order_id", id))
		outOrder.dealUserId = getContext().userId
		outOrder.status = Status.NO_PASS
		if (!details.isNullOrEmpty()) {
			for (detail in details) {
				detail.status = Status.NO_PASS
				warehouseOutOrderDetailMapper.updateById(detail)
			}
		}
		warehouseOutOrderMapper.updateById(outOrder)
		return returnSuccess()

	}

	override fun cancelOutOrder(id: Long): ResponseBody {
		log.info("仓库订单管理：取消出库：id{}", id)
		val outOrder =
			warehouseOutOrderMapper.selectById(id) ?: return returnError(ErrorCode.DATA_IS_NOT_FIND, "未找到出库单")
		if (outOrder.status != Status.WAIT_AUDIT) {
			return returnError(ErrorCode.OPERATION_DATA_ERROR, "订单已被处理")
		}
		val details =
			warehouseOutOrderDetailMapper.selectList(QueryWrapper<WarehouseOutOrderDetail?>().eq("out_order_id", id))
		outOrder.dealUserId = getContext().userId
		outOrder.status = Status.SCRAP
		if (!details.isNullOrEmpty()) {
			for (detail in details) {
				detail.status = Status.SCRAP
				warehouseOutOrderDetailMapper.updateById(detail)
			}
		}
		warehouseOutOrderMapper.updateById(outOrder)
		return returnSuccess()

	}

	override fun deleteOutOrder(id: Long): ResponseBody {
		log.info("出库单 ==>出库单删除：id{}", id)
		val outOrder = warehouseOutOrderMapper.selectById(id)?: return returnSuccess()
		if(outOrder.status.code > Status.WAIT_AUDIT.code){
			return returnError(ErrorCode.DATA_DELETE_FAILED,"订单已被处理")
		}
		warehouseOutOrderMapper.deleteById(id)
		return returnSuccess()
	}
}
